package com.softserveinc.ita.kaiji.web.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.softserveinc.ita.kaiji.dto.GameInfoDto;
import com.softserveinc.ita.kaiji.service.GameService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.softserveinc.ita.kaiji.model.player.bot.Bot;
import com.softserveinc.ita.kaiji.service.GameServiceImpl;



/**
 * Controller for New Game form
 * @author Boiko Eduard
 * @version 1.1
 * @since 17.03.14 
 */


@Controller
@RequestMapping("/game/new")
public class CreateGameController {

    private static Logger logger = Logger.getLogger(CreateGameController.class);

    @Autowired
    private GameService gameService;

    @RequestMapping(method = RequestMethod.GET)
    public String sendToForm(Model model, HttpServletResponse response){
    	
			logger.trace("CreateGameController got GET-request");
        
        GameInfoDto gameInfoDtoImpl = new GameInfoDto();
        gameInfoDtoImpl.setGameName("Duel");
        gameInfoDtoImpl.setPlayerName("Zoro");
        gameInfoDtoImpl.setNumberOfCards(3);
        gameInfoDtoImpl.setBotType(Bot.Types.MEDIUM);
        model.addAttribute("gameInfo", gameInfoDtoImpl);
		response.addCookie(new Cookie("personId",null));
		
			logger.trace("gameInfoDtoImpl added to the model and will be sent to form");
    	
        return "create-game";
    }
    
    @RequestMapping(method = RequestMethod.POST)
    public String initForm(@ModelAttribute("gameInfo") @Valid GameInfoDto gameInfoDto,
    						BindingResult br, HttpServletResponse response, Model model){
    	
			logger.trace("Checkin BindingResult for mistakes");
        
		if (br.hasErrors()) {
			logger.info("Registration failed: gameInfo model NOT VALID");
			return "create-game";
		}

		Integer gameId = gameService.createGame(gameInfoDto);
		
			logger.trace("Game created. gameId will be passed to PlayGameController");		
    	
		Integer playerId = null;
		playerId =gameService.getPlayerIdFromGame(gameId);
		response.addCookie(new Cookie("personId", playerId.toString()));
		
			logger.trace("Player_temp id added to cookies (personId)");
    	
		return "forward:/game/"+gameId+"/";
        
    }
    
}
